import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tooltip,
  Rate,
  Checkbox,
  Tabs,
} from 'antd';
import IconButton from '@/components/IconButton';
import RegionSelectModal from '../../pages/Base/Region/RegionSelectModal';
import styles from './index.less';
import { REGION_ADDRESS_TYPE, REGION_TYPE, SERVICE_STATUS } from '@/Constants';
import api from '@/api';
import { maxLength } from '@/utils/form';
import arrowImg from '@/assets/imgs/long_arrow@2x.png';

const FormItem = Form.Item;
const { TextArea, Search } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

@Form.create()
class ProductRangeForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      regionVisible: false,
      regionItems: [],
      selectedItems: [],
      help: '',
      validateStatus: '',
      destinationRegionVisible: false,
      destinationRegionItems: [],
      destinationSelectedItems: [],
      destinationHelp: '',
      destinationValidateStatus: '',
    };
  }

  componentWillUnmount() {
    // 卸载异步操作设置状态
    this.setState = (state, callback) => {
      return;
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    if (this.props.isUpdate) {
      const { currentRegion, keyIndex, handleSaveRange } = this.props;
      const { regionItems, destinationRegionItems } = this.state;
      const startItems = currentRegion.startItems || [];
      const endItems = currentRegion.endItems || [];
      try {
        this.setState({
          regionItems: startItems,
          destinationRegionItems: endItems,
          selectedItems:
            startItems.length > 0
              ? startItems.map(item => {
                const region = item[item.length - 1];
                return {
                  ...region,
                  key: region.code,
                };
              })
              : [],
          destinationSelectedItems:
            endItems.length > 0
              ? endItems.map(item => {
                const region = item[item.length - 1];
                return {
                  ...region,
                  key: region.code,
                };
              })
              : [],
        });
        handleSaveRange({
          keyIndex,
          regionItems: startItems,
          destinationRegionItems: endItems,
        });
      } catch (error) {
        throw error;
      }
    }
  }

  // 起点新增按钮
  toggleModalVisible = flag => {
    this.setState({
      regionVisible: !!flag,
    });
  };
  // 终点新增按钮
  toggleModalVisible2 = flag => {
    this.setState({
      destinationRegionVisible: !!flag,
    });
  };

  // 起点保存
  handleSave = (selectedItems, regionItems) => {
    const { handleSaveRange, keyIndex } = this.props;
    this.setState({
      selectedItems,
      regionItems,
    });
    handleSaveRange({
      keyIndex,
      regionItems,
    });
  };
  // 终点保存
  handleDestinationSave = (selectedItems, regionItems) => {
    const { handleSaveRange, keyIndex } = this.props;
    this.setState({
      destinationSelectedItems: selectedItems,
      destinationRegionItems: regionItems,
    });
    handleSaveRange({
      keyIndex,
      destinationRegionItems: regionItems,
    });
  };

  // 起点国家区域/机场的变更
  handleChangeOriginRegion = selectedItems => {
    const { regionItems } = this.state;
    let newItems = selectedItems.map(item => ({
      key: item.key,
      name: item.name || item.label,
      code: item.code || item.key,
    }));
    let newRegionItems = [...regionItems];
    newRegionItems = newRegionItems.filter(regionItem =>
      newItems.some(newItem => newItem.key === regionItem[regionItem.length - 1].key)
    );
    this.setState({
      selectedItems: newItems,
      regionItems: newRegionItems,
    });
  };

  // 终点国家区域/机场的变更
  handleChangeDestinationRegion = selectedItems => {
    const { destinationRegionItems } = this.state;
    const { handleSaveRange, key } = this.props;
    let newItems = selectedItems.map(item => ({
      key: item.key,
      name: item.name || item.label,
      code: item.code || item.key,
    }));
    let newRegionItems = [...destinationRegionItems];
    newRegionItems = newRegionItems.filter(regionItem =>
      newItems.some(newItem => newItem.code === regionItem[regionItem.length - 1].code)
    );
    this.setState({
      destinationSelectedItems: newItems,
      destinationRegionItems: newRegionItems,
    });
  };
  // 检验起点/终点是否为空
  checkRegions = () => {
    const { regionItems, destinationRegionItems } = this.state;
    if (regionItems.length === 0 && destinationRegionItems.length === 0) {
      this.setState({
        validateStatus: 'error',
        help: '起点区域不能为空',
        destinationValidateStatus: 'error',
        destinationHelp: '终点区域不能为空',
      });
      return true;
    } else if (regionItems.length === 0 && destinationRegionItems.length) {
      this.setState({
        validateStatus: 'error',
        help: '起点区域不能为空',
        destinationValidateStatus: '',
        destinationHelp: '',
      });
      return true;
    } else if (destinationRegionItems.length === 0 && regionItems.length) {
      this.setState({
        validateStatus: '',
        help: '',
        destinationValidateStatus: 'error',
        destinationHelp: '终点区域不能为空',
      });
      return true;
    } else {
      this.setState({
        validateStatus: '',
        help: '',
        destinationValidateStatus: '',
        destinationHelp: '',
      });
    }
    return false;
  };

  // 显示区域文字
  showRegionText = item => {
    const { type, viewId } = this.props;
    let isAirProduct =
      (viewId === 'product' && type === '1') || (viewId === 'service' && type === 'AIR');
    let regionAddressType = isAirProduct ? REGION_ADDRESS_TYPE.AIR_PORT : REGION_ADDRESS_TYPE.AREA;
    if (regionAddressType === REGION_ADDRESS_TYPE.AIR_PORT) {
      return `${item.name}(${item.code})`;
    } else {
      return item.name;
    }
  };

  // 校验始发和终点
  validateAddress = () => {
    const { type, viewId } = this.props;
    let isAirProduct =
      (viewId === 'product' && type === '1') || (viewId === 'service' && type === 'AIR');
    const Transtype = isAirProduct ? REGION_ADDRESS_TYPE.AIR_PORT : REGION_ADDRESS_TYPE.AREA;
    if (
      [REGION_ADDRESS_TYPE.AREA, REGION_ADDRESS_TYPE.AIR_PORT].includes(Transtype) &&
      this.checkRegions()
    ) {
      return false;
    } else {
      return true;
    }
  };

  render() {
    const { form, viewId, type } = this.props;
    const {
      regionVisible,
      destinationRegionVisible,
      regionItems,
      selectedItems,
      help,
      validateStatus,
      destinationHelp,
      destinationValidateStatus,
      destinationSelectedItems,
      destinationRegionItems,
    } = this.state;
    let isAirProduct =
      (viewId === 'product' && type === '1') || (viewId === 'service' && type === 'AIR');
    const Transtype = isAirProduct ? REGION_ADDRESS_TYPE.AIR_PORT : REGION_ADDRESS_TYPE.AREA;

    // 起点
    const regionSelectProps = {
      modalVisible: regionVisible,
      handleModalVisible: this.toggleModalVisible,
      handleSave: this.handleSave,
      regionAddressType: isAirProduct ? REGION_ADDRESS_TYPE.AIR_PORT : REGION_ADDRESS_TYPE.AREA,
      selectedItems,
      regionItems,
    };
    // 终点
    const regionSelectProps2 = {
      modalVisible: destinationRegionVisible,
      handleModalVisible: this.toggleModalVisible2,
      handleSave: this.handleDestinationSave,
      regionAddressType: isAirProduct ? REGION_ADDRESS_TYPE.AIR_PORT : REGION_ADDRESS_TYPE.AREA,
      selectedItems: destinationSelectedItems,
      regionItems: destinationRegionItems,
    };

    return (
      <>
        <Row type="flex" gutter={16}>
          <Col span={9}>
            <FormItem
              wrapperCol={{ span: 22 }}
              className={styles.regionFormItem}
              help={help}
              validateStatus={validateStatus}
            >
              <Select
                mode="tags"
                value={selectedItems}
                labelInValue
                optionLabelProp="text"
                style={{ width: '100%' }}
                disabled
                open={false}
                onChange={this.handleChangeOriginRegion}
              >
                {selectedItems.length &&
                  selectedItems.map(item => (
                    <Option key={item.key} value={item.key} text={this.showRegionText(item)} />
                  ))}
              </Select>
              <IconButton
                style={{ position: 'absolute', top: -7, right: -35 }}
                icon="icon-edit"
                title="选择起点"
                onClick={() => this.setState({ regionVisible: true })}
              />
            </FormItem>
          </Col>
          <Col span={5}>
            <div className={styles.arrowStyle}>
              <img src={arrowImg} className={styles.arrow} />
            </div>
          </Col>
          <Col span={9}>
            <FormItem
              wrapperCol={{ span: 22 }}
              className={styles.regionFormItem}
              help={destinationHelp}
              validateStatus={destinationValidateStatus}
            >
              <Select
                mode="tags"
                value={destinationSelectedItems}
                labelInValue
                optionLabelProp="text"
                style={{ width: '100%' }}
                disabled
                open={false}
                onChange={this.handleChangeDestinationRegion}
              >
                {destinationSelectedItems.length &&
                  destinationSelectedItems.map(item => (
                    <Option key={item.key} value={item.key} text={this.showRegionText(item)} />
                  ))}
              </Select>
              <IconButton
                style={{ position: 'absolute', top: -7, right: -35 }}
                icon="icon-edit"
                title="选择终点"
                onClick={() => this.setState({ destinationRegionVisible: true })}
              />
            </FormItem>
          </Col>
        </Row>
        <RegionSelectModal {...regionSelectProps} />
        <RegionSelectModal {...regionSelectProps2} />
      </>
    );
  }
}

export default ProductRangeForm;
